package com.example.view;

import com.example.entry.HeaderEntry;
import javafx.application.Platform;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TablePosition;
import javafx.scene.control.TableView;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;
import javafx.util.converter.DefaultStringConverter;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.WebSocket;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;


public class WebSocketView {
    @FXML
    private TextField nameField;
    @FXML
    private Button saveButton;
    @FXML
    private Button resetButton;
    @FXML
    private Button switchToHttpButton;
    @FXML
    private TextField wsUrlField;
    @FXML
    private Button connectButton;
    @FXML
    private TextArea messageArea;
    @FXML
    private Button sendButton;
    @FXML
    private TableView<HeaderEntry> headersTable;
    @FXML
    private TableView<HeaderEntry> cookiesTable;
    @FXML
    private TextArea responseArea;
    @FXML
    private Button clearButton;
    @FXML
    private Button addHeaderButton;
    @FXML
    private Button addCookieButton;

    private WebSocket.Builder wsBuilder;
    private WebSocket webSocket;
    private HttpClient client;

    @FXML
    public void initialize() {
        // 初始化 HttpClient 和 WebSocket.Builder
        client = HttpClient.newHttpClient();
        wsBuilder = client.newWebSocketBuilder();

        // 初始化表格
        initHeadersTable(headersTable);
        initHeadersTable(cookiesTable);

        // 添加初始空行
        headersTable.getItems().add(new HeaderEntry());
        cookiesTable.getItems().add(new HeaderEntry());

        // 按钮事件
        connectButton.setOnAction(e -> connect());
        sendButton.setOnAction(e -> sendMessage());
        resetButton.setOnAction(e -> resetForm());

        // 添加切换回HTTP的按钮事件
        switchToHttpButton.setOnAction(e -> {
            try {
                // 加载HTTP界面
                Parent root = new FXMLLoader(this.getClass().getResource("WebHttpView.fxml")).load();
                // 创建新的场景
                Scene scene = new Scene(root);
                // 获取当前窗口并设置新场景
                Stage stage = (Stage) switchToHttpButton.getScene().getWindow();
                stage.setScene(scene);

            } catch (IOException ex) {
                showAlert("错误", "加载HTTP界面失败: " + ex.getMessage(), Alert.AlertType.ERROR);
            }
        });

        // 添加清空按钮事件
        clearButton.setOnAction(e -> clearMessages());

        // 添加表格按钮事件
        addHeaderButton.setOnAction(e -> addHeader());
        addCookieButton.setOnAction(e -> addCookie());
    }

    private void connect() {
        String url = wsUrlField.getText().trim();
        if (url.isEmpty()) {
            showAlert("错误", "请输入WebSocket URL", Alert.AlertType.ERROR);
            return;
        }

        // 如果已经连接，先断开
        if (webSocket != null) {
            webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "用户断开连接");
            webSocket = null;
            connectButton.setText("连接");
            return;
        }

        try {
            // 构建WebSocket连接
            WebSocket.Builder builder = client.newWebSocketBuilder();

            // 添加Headers
            for (HeaderEntry header : headersTable.getItems()) {
                if (header.getName() != null && !header.getName().trim().isEmpty()) {

                    builder.header(header.getName(), header.getValue());
                }
            }

            // 添加Cookies
            StringBuilder cookieStr = new StringBuilder();
            for (HeaderEntry cookie : cookiesTable.getItems()) {
                if (cookie.getName() != null && !cookie.getName().trim().isEmpty()) {
                    if (cookieStr.length() > 0) {
                        cookieStr.append("; ");
                    }
                    cookieStr.append(cookie.getName()).append("=").append(cookie.getValue());
                }
            }
            if (cookieStr.length() > 0) {
                builder.header("Cookie", cookieStr.toString());
            }

            // 创建WebSocket连接
            webSocket = builder.buildAsync(URI.create(url), new WebSocket.Listener() {
                StringBuilder messageBuffer = new StringBuilder();

                @Override
                public void onOpen(WebSocket webSocket) {
                    Platform.runLater(() -> {
                        responseArea.appendText("WebSocket连接已建立\n");
                        connectButton.setText("断开");
                    });
                    // 初始化第一次消息请求
                    webSocket.request(1);
                }

                @Override
                public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
                    messageBuffer.append(data);

                    if (last) {
                        String fullMessage = messageBuffer.toString();
                        messageBuffer.setLength(0); // 清空缓冲区

                        Platform.runLater(() -> {
                            responseArea.appendText("收到消息: " + fullMessage + "\n");
                        });
                    }

                    // 立即请求下一条消息
                    webSocket.request(1);
                    return CompletableFuture.completedFuture(null);
                }

                @Override
                public void onError(WebSocket webSocket, Throwable error) {
                    Platform.runLater(() -> {
                        responseArea.appendText("错误: " + error.getMessage() + "\n");
                        connectButton.setText("连接");
                    });
                }

                @Override
                public CompletionStage<?> onClose(WebSocket webSocket, int statusCode, String reason) {
                    Platform.runLater(() -> {
                        responseArea.appendText("连接已关闭，状态码: " + statusCode + ", 原因: " + reason + "\n");
                        connectButton.setText("连接");
                    });
                    return CompletableFuture.completedFuture(null);
                }
            }).join();


        } catch (Exception e) {
            showAlert("错误", "WebSocket连接失败: " + e.getMessage(), Alert.AlertType.ERROR);
        }
    }

    private void sendMessage() {
        if (webSocket == null) {
            showAlert("错误", "请先建立WebSocket连接", Alert.AlertType.WARNING);
            return;
        }

        String message = messageArea.getText().trim();
        if (message.isEmpty()) {
            showAlert("错误", "请输入要发送的消息", Alert.AlertType.WARNING);
            return;
        }

        webSocket.sendText(message, true);
        responseArea.appendText("发送消息: " + message + "\n");
    }

    private void resetForm() {
        nameField.clear();
        wsUrlField.clear();
        messageArea.clear();
        responseArea.clear();
        headersTable.getItems().clear();
        cookiesTable.getItems().clear();

        // 添加初始空行
        headersTable.getItems().add(new HeaderEntry());
        cookiesTable.getItems().add(new HeaderEntry());

        // 如果有连接，断开它
        if (webSocket != null) {
            webSocket.sendClose(WebSocket.NORMAL_CLOSURE, "重置表单");
            webSocket = null;
            connectButton.setText("连接");
        }
    }

    private void showAlert(String title, String content, Alert.AlertType alertType) {
        Platform.runLater(() -> {
            Alert alert = new Alert(alertType);
            alert.setTitle(title);
            alert.setHeaderText(null);
            alert.setContentText(content);
            alert.show();
        });
    }

    private void initHeadersTable(TableView<HeaderEntry> table) {

        table.setEditable(true);

        // 获取表格的列
        TableColumn<HeaderEntry, String> nameCol = (TableColumn<HeaderEntry, String>) table.getColumns().get(0);
        TableColumn<HeaderEntry, String> valueCol = (TableColumn<HeaderEntry, String>) table.getColumns().get(1);
        TableColumn<HeaderEntry, Void> actionCol = (TableColumn<HeaderEntry, Void>) table.getColumns().get(2);

        // 设置列的值工厂
        nameCol.setCellValueFactory(cellData -> cellData.getValue().nameProperty());
        valueCol.setCellValueFactory(cellData -> cellData.getValue().valueProperty());

        // 修改单元格工厂，在编辑状态变化时保存数据
        nameCol.setCellFactory(column -> {
            TextFieldTableCell<HeaderEntry, String> cell = new TextFieldTableCell<>(new DefaultStringConverter());

            // 添加编辑状态监听
            cell.editingProperty().addListener((obs, oldVal, newVal) -> {

                // 当编辑结束时（从true变为false）
                if (oldVal && !newVal) {
                    // 获取编辑器中的文本
                    TextField textField = (TextField) cell.getGraphic();
                    String newValue = textField != null ? textField.getText() : cell.getItem();

                    HeaderEntry entry = cell.getTableRow().getItem();

                    if (entry != null) {
                        entry.setName(newValue != null ? newValue : "");

                        // 检查当前行的数据
                        String name = entry.getName();
                        String value = entry.getValue();

                        // 如果当前行有数据，并且是最后一行，则添加新行
                        if ((name != null && !name.trim().isEmpty()) ||
                                (value != null && !value.trim().isEmpty())) {
                            int currentIndex = cell.getTableRow().getIndex();
                            int totalRows = table.getItems().size();

                            if (currentIndex == table.getItems().size() - 1) {
                                table.getItems().add(new HeaderEntry());
                            }
                        }
                        table.refresh();
                    }
                }
            });

            return cell;
        });

        valueCol.setCellFactory(column -> {
            TextFieldTableCell<HeaderEntry, String> cell = new TextFieldTableCell<>(new DefaultStringConverter());

            // 添加编辑状态监听
            cell.editingProperty().addListener((obs, oldVal, newVal) -> {

                // 当编辑结束时（从true变为false）
                if (oldVal && !newVal) {
                    // 获取编辑器中的文本
                    TextField textField = (TextField) cell.getGraphic();
                    String newValue = textField != null ? textField.getText() : cell.getItem();

                    HeaderEntry entry = cell.getTableRow().getItem();

                    if (entry != null) {
                        entry.setValue(newValue != null ? newValue : "");

                        // 检查当前行的数据
                        String name = entry.getName();
                        String value = entry.getValue();

                        // 如果当前行有数据，并且是最后一行，则添加新行
                        if ((name != null && !name.trim().isEmpty()) ||
                                (value != null && !value.trim().isEmpty())) {
                            int currentIndex = cell.getTableRow().getIndex();
                            if (currentIndex == table.getItems().size() - 1) {
                                table.getItems().add(new HeaderEntry());
                            }
                        }
                        table.refresh();
                    }
                }
            });

            return cell;
        });

        // 设置操作列
        actionCol.setCellFactory(param -> new TableCell<>() {
            private final Button saveButton = new Button("保存");
            private final Button deleteButton = new Button("删除");
            private final HBox container = new HBox(5);

            {
                container.getChildren().addAll(saveButton, deleteButton);
                container.setAlignment(Pos.CENTER_RIGHT);  // 设置靠右对齐

                // 设置单元格右对齐
                setAlignment(Pos.CENTER_RIGHT);

                // 保存按钮事件
                saveButton.setOnAction(event -> {
                    HeaderEntry entry = getTableView().getItems().get(getIndex());
                    if (entry != null) {
                        // 获取当前编辑的单元格
                        TablePosition<?, ?> editingCell = getTableView().getEditingCell();
                        if (editingCell != null) {
                            // 获取当前正在编辑的单元格所在的行和列
                            int row = editingCell.getRow();
                            int col = editingCell.getColumn();

                            // 获取正在编辑的TableColumn
                            TableColumn<HeaderEntry, ?> column = getTableView().getColumns().get(col);

                            // 获取编辑器中的文本
                            TableCell<?, ?> cell = getTableCell(row, col);
                            if (cell instanceof TextFieldTableCell) {
                                TextField textField = (TextField) ((TextFieldTableCell) cell).getGraphic();
                                if (textField != null) {
                                    String newValue = textField.getText();
                                    // 根据列更新相应的值
                                    if (column == nameCol) {
                                        entry.setName(newValue);
                                    } else if (column == valueCol) {
                                        entry.setValue(newValue);
                                    }
                                }
                            }
                            // 结束编辑状态
                            getTableView().edit(-1, null);
                        }


                        // 如果当前行有数据，并且是最后一行，则添加新行
                        if (!entry.getName().trim().isEmpty() || !entry.getValue().trim().isEmpty()) {
                            int currentIndex = getIndex();
                            if (currentIndex == getTableView().getItems().size() - 1) {
                                getTableView().getItems().add(new HeaderEntry());
                            }
                        }

                        getTableView().refresh();
                    }
                });

                // 删除按钮事件
                deleteButton.setOnAction(event -> {
                    HeaderEntry entry = getTableView().getItems().get(getIndex());
                    getTableView().getItems().remove(entry);
                    // 如果表格为空，添加一个新的空行
                    if (getTableView().getItems().isEmpty()) {
                        getTableView().getItems().add(new HeaderEntry());
                    }
                });
            }

            // 辅助方法：获取指定位置的TableCell
            private TableCell<?, ?> getTableCell(int row, int column) {
                for (Node node : getTableView().lookupAll(".table-cell")) {
                    if (node instanceof TableCell) {
                        TableCell<?, ?> cell = (TableCell<?, ?>) node;
                        if (cell.getIndex() == row && cell.getTableColumn() != null
                                && getTableView().getColumns().indexOf(cell.getTableColumn()) == column) {
                            return cell;
                        }
                    }
                }
                return null;
            }

            @Override
            protected void updateItem(Void item, boolean empty) {
                super.updateItem(item, empty);
                if (empty) {
                    setGraphic(null);
                } else {
                    setGraphic(container);
                }
            }
        });

    }

    // 添加新的方法来处理添加按钮事件
    @FXML
    private void addHeader() {
        headersTable.getItems().add(new HeaderEntry());
    }

    @FXML
    private void addCookie() {
        cookiesTable.getItems().add(new HeaderEntry());
    }


    private void clearMessages() {
        responseArea.clear();
    }
}
